package com.jnxx.agent.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jnxx.basic.domain.TagProxy;
import com.jnxx.basic.dto.AgentInfoDTO;
import com.jnxx.basic.util.AjaxResult;
import com.jnxx.basic.util.HttpTool;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Field;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/agent")
public class AgentController {


    private static final Map<String, String> MAPPING = new HashMap<>();
    static {
        // 初始化映射
        MAPPING.put("gmtCreate", "创建时间");
        MAPPING.put("gmtModified", "修改时间");
        MAPPING.put("account", "代理账号");
        MAPPING.put("price", "余额");
        MAPPING.put("agentCode", "代理编码");
        MAPPING.put("secretKey", "密钥");
        MAPPING.put("callbackUrl", "回调地址");
        MAPPING.put("descs", "备注");
        MAPPING.put("thoroughfareName", "通道组名称");
        MAPPING.put("polling", "轮询状态");
        MAPPING.put("agentIP", "ip地址");
        MAPPING.put("phone", "代理手机号");
        MAPPING.put("creditPrice", "授信额度");
        MAPPING.put("adminName", "商务负责人");
        MAPPING.put("apiVersion", "接口版本号");
        MAPPING.put("contractNumber", "合同号");
        MAPPING.put("bankAccount", "银行账户");
        MAPPING.put("back", "开户行");
        MAPPING.put("swarmRobot", "机器人标志");
        MAPPING.put("alertTime", "账户提醒");
        MAPPING.put("cache", "订单缓存");
    }
    /**
     * 查询代理分页列表
     * @return
     */
    @PostMapping("/agentQueryList")
    public AjaxResult agentQueryList(@RequestBody Map<String, String> map){
        String url = "http://127.0.0.1:8068/api/xc/agentList";

        String res = HttpTool.sendPost(url, map);

        JSONObject jsonObject = JSONObject.parseObject(res);
        JSONObject data = jsonObject.getJSONObject("data");
        String code = jsonObject.getString("code");
        if ("200".equals(code)){
            return AjaxResult.success(data);
        }
        return null;
    }

    /**
     * 查询单个代理详情
     * @param agentId
     * @return
     */
    @GetMapping("/agentDetail/{agentId}")
    public AjaxResult agentDetail(@PathVariable("agentId") String agentId) throws IllegalAccessException {

        String url = "http://127.0.0.1:8068/api/xc/agentInfo/"+agentId;
        String res = HttpTool.sendGet(url,new HashMap<String,String>());
        JSONObject jsonObject = JSONObject.parseObject(res);

        String code = jsonObject.getString("code");
        String errorMsg = jsonObject.getString("errorMsg");
        if ("200".equals(code)){
            AgentInfoDTO data = jsonObject.getObject("data",AgentInfoDTO.class);
            Integer agentStatus = data.getAgentStatus();
            String archives = data.getArchives();
            List<TagProxy> tagProxys = data.getTagProxys();
            Integer creditRating = data.getCreditRating();
            String agentName = data.getAgentName();
            System.out.println("返回参数"+JSON.toJSONString(data));
            HashMap<String, Object> resp = new HashMap<>();
            resp.put("agentStatus",agentStatus);
            resp.put("archives",archives);
            resp.put("tagProxys",tagProxys);
            resp.put("agentName",agentName);
            resp.put("creditRating",creditRating);
            resp.put("data",toMap(data));
            return AjaxResult.success(resp);
        }else {
            return AjaxResult.error("-1",errorMsg);
        }
    }

    /*代理订单统计*/
    @PostMapping("/queryAgentConsum")
    public AjaxResult queryAgentConsum(@RequestBody HashMap<String,Object> queryParams){

        try {
            String url = "http://127.0.0.1:8068/api/xc/agentConsumOrderChart";
            String res = HttpTool.sendPost2(url, queryParams);
            JSONObject jsonObject = JSONObject.parseObject(res);
            String code = jsonObject.getString("code");
            String errorMsg = jsonObject.getString("errorMsg");
            if ("200".equals(code)){
                JSONObject data = jsonObject.getJSONObject("data");
                return AjaxResult.success(data);
            }
            return AjaxResult.error("-1","系统繁忙，请稍后再试！");
        }catch (Exception e){
            return AjaxResult.error("-1","系统繁忙，请稍后再试！");
        }
    }

    /*代理毛利润统计*/
    @PostMapping("/agentProfitChart")
    public AjaxResult agentProfitChart(@RequestBody HashMap<String,Object> queryParams){

        try {
            String url = "http://127.0.0.1:8068/api/xc/agentProfitChart";
            String res = HttpTool.sendPost2(url, queryParams);
            JSONObject jsonObject = JSONObject.parseObject(res);
            String code = jsonObject.getString("code");
            String errorMsg = jsonObject.getString("errorMsg");
            if ("200".equals(code)){
                JSONArray data = jsonObject.getJSONArray("data");
                return AjaxResult.success(data);
            }
            return AjaxResult.error("-1","系统繁忙，请稍后再试！");
        }catch (Exception e){
            return AjaxResult.error("-1","系统繁忙，请稍后再试！");
        }
    }

    /*代理消耗统计*/
    @PostMapping("/agentConsumeChart")
    public AjaxResult agentConsumeChart(@RequestBody HashMap<String,Object> queryParams){

        try {
            String url = "http://127.0.0.1:8068/api/xc/agentConsumeChart";
            String res = HttpTool.sendPost2(url, queryParams);
            JSONObject jsonObject = JSONObject.parseObject(res);
            String code = jsonObject.getString("code");
            String errorMsg = jsonObject.getString("errorMsg");
            if ("200".equals(code)){
                JSONArray data = jsonObject.getJSONArray("data");
                return AjaxResult.success(data);
            }
            return AjaxResult.error("-1","系统繁忙，请稍后再试！");
        }catch (Exception e){
            return AjaxResult.error("-1","系统繁忙，请稍后再试！");
        }
    }


    public static ArrayList<HashMap<String, Object>> toMap(AgentInfoDTO dto) throws IllegalAccessException {
        ArrayList<HashMap<String, Object>> result = new ArrayList<>();
        Field[] fields = AgentInfoDTO.class.getDeclaredFields();
        int i = 0;
        for (Field field : fields) {
            field.setAccessible(true);
            String fieldName = field.getName();
            String chineseFieldName = MAPPING.getOrDefault(fieldName, fieldName); // 获取中文字段名
            if (MAPPING.containsKey(fieldName)) {
                HashMap<String, Object> data = new HashMap<>();
                data.put("name",chineseFieldName);
                data.put("text",field.get(dto));
                data.put("dataKey",fieldName);
                data.put("id",i);
                i++;
                result.add(data);
            }
        }
        return result;
    }






    /**
     * 查询代理列表
     * @return
     */
    @PostMapping("/agentList")
    public Object agentList(@RequestBody Map<String, String> map){
        String url = "http://127.0.0.1:8068/api/xc/agentList";
//        String url = "http://47.110.49.47:8068/api/xc/agentList";
        String res = HttpTool.sendPost(url, map);

        JSONObject jsonObject = JSONObject.parseObject(res);
        JSONObject data = jsonObject.getJSONObject("data");

        String code = jsonObject.getString("code");
        if ("200".equals(code)){
            return data;
        }
        return null;
    }


    @PostMapping("/agentForProductList")
    public Object agentForProductList(@RequestBody Map<String, String> map){
        String url = "http://127.0.0.1:8068/api/xc/agentForProductList";
//        String url = "http://47.110.49.47:8068/api/xc/agentForProductList";
        String res = HttpTool.sendPost(url, map);

        JSONObject jsonObject = JSONObject.parseObject(res);
        JSONObject data = jsonObject.getJSONObject("data");
        String code = jsonObject.getString("code");
        if ("200".equals(code)){
            return data;
        }
        return null;
    }


}
